﻿using RSSReader.WebClient.Framework;
using RSSReader.WebClient.Models;
using RSSReader.WebClient.WCFWebRoleService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Xml.Linq;
using WebMatrix.WebData;

namespace RSSReader.WebClient.Controllers
{

  [Authorize]
  public class HomeController : Controller
  {
    //[Authorize]
    public ActionResult Index()
    {
      HomePageModel Model = new HomePageModel();

      if (User.Identity.IsAuthenticated)
      {
        DataDistributorClient client = new DataDistributorClient();
        var ConnectedUser = (UserIdentity)(User.Identity);
        Model.Sources = client.GetSubscriptions(ConnectedUser.UserData.UserId).Select(s => new FeedSource(s)).OrderBy(b => b.Title).ToList();
      }

      return View(Model);
    }

    public PartialViewResult AddSource(string source)
    {
      FeedSource Model = null;
      XDocument rssFeed;
      try
      {
        rssFeed = XDocument.Load(source);
      }
      catch (Exception e)
      {
        rssFeed = null;
      }

      if (rssFeed != null)
      {
        var Channel = rssFeed.Descendants("channel").FirstOrDefault();

        if (Channel != null)
        {
          var Desc = Channel.Element("description");
          var Title = Channel.Element("title");

          if (Title != null && Desc != null)
            Model = new FeedSource { Link = source, Title = Title.Value, Description = Desc.Value };
        }
      }

      //if (Model == null)
      //  Model = new FeedSource { Description = "Erreur", Link = "Erreur", Title = "Erreur" };
      //else 

      if (User.Identity.IsAuthenticated && Model != null)
      {
        DataDistributorClient client = new DataDistributorClient();
        var ConnectedUser = (UserIdentity)(User.Identity);

        var Subscription = new UserSubscriptionInformation { Url = source, IsSubscribe = true, Description = Model.Description, Title = Model.Title };

        client.SetSubscriptions(new UserSubscriptionInformation[] { Subscription }, ConnectedUser.UserData.UserId);
      }

      return PartialView("SourceListItem", Model);
    }

    public JsonResult Unsubscribe(string sourceLink)
    {
      if (User.Identity.IsAuthenticated)
      {
        DataDistributorClient client = new DataDistributorClient();
        var ConnectedUser = (UserIdentity)(User.Identity);
        client.RemoveSubscriptions(new string[] { sourceLink }, ConnectedUser.UserData.UserId);
      }
      return Json(true, JsonRequestBehavior.DenyGet);
    }

    public JsonResult UpdateArticleStatus(string sourceUrl, string articleUrl, bool IsFavorite)
    {
      if (User.Identity.IsAuthenticated)
      {

        var rssFeed = XDocument.Load(sourceUrl);
        var Desc = rssFeed.Descendants("channel").FirstOrDefault().Element("description");
        var Title = rssFeed.Descendants("channel").FirstOrDefault().Element("title");

        if (Desc != null && Title != null)
        {
          var Article = (from item in rssFeed.Descendants("item")
                         where item.Element("link") != null && item.Element("link").Value == articleUrl
                         select new FeedArticle(item)).FirstOrDefault();
          if (Article != null)
          {
            DataDistributorClient client = new DataDistributorClient();
            var ConnectedUser = (UserIdentity)(User.Identity);

            var UserSub = new UserSubscriptionInformation
            {
              Description = Desc.Value,
              Url = sourceUrl,
              Title = Title.Value,
            };

            var UserArticle = new UserArticleInformation
            {
              Description = Article.Description,
              IsFavorite = IsFavorite,
              PublicationDate = Article.PublicationDate,
              Title = Article.Title,
              Url = articleUrl,
            };

            Dictionary<UserSubscriptionInformation, UserArticleInformation[]> Dictionary = new Dictionary<UserSubscriptionInformation, UserArticleInformation[]>
            {
              { UserSub, new UserArticleInformation[]{ UserArticle }},
            };

            client.UpdateUserArticles(Dictionary, ConnectedUser.UserData.UserId);
          }
        }
      }

      return Json(true, JsonRequestBehavior.DenyGet);
    }

    public PartialViewResult GetFeedArticle(List<FeedSource> sources)
    {
      List<FeedArticle> Articles = new List<FeedArticle>();
      if (sources != null)
      {
        foreach (var src in sources)
        {
          var ArticlesToAdd = GetRssFeeds(src.Link).ToList();
          for (int i = 0; i < ArticlesToAdd.Count; ++i)
          {
            ArticlesToAdd[i].SourceName = src.Title;
            ArticlesToAdd[i].SourceLink = src.Link;
          }
          Articles.AddRange(ArticlesToAdd);
        }

        if (User.Identity.IsAuthenticated)
        {
          DataDistributorClient client = new DataDistributorClient();
          var ConnectedUser = (UserIdentity)(User.Identity);

          var UserArticles = client.GetUserArticles(Articles.Select(s => s.Link).ToArray(), ConnectedUser.UserData.UserId);

          foreach (var key in UserArticles.Keys)
          {
            foreach (var UserArticle in UserArticles[key])
            {
              var Article = Articles.Where(w => w.Link == UserArticle.Url).FirstOrDefault();
              Article.IsFavorite = UserArticle.IsFavorite;
              Article.HaveBeenRed = true;
            }
          }
        }
      }

      return PartialView("FeedArticlesList", Articles.OrderByDescending(o => o.PublicationDate));
    }

    public PartialViewResult GetFavoritesArticles()
    {
      List<FeedArticle> Articles = new List<FeedArticle>();

      if (User.Identity.IsAuthenticated)
      {
        DataDistributorClient client = new DataDistributorClient();
        var ConnectedUser = (UserIdentity)(User.Identity);
        var Favorites = client.GetUserFavorites(ConnectedUser.UserData.UserId);
        foreach (var key in Favorites.Keys)
          Articles.AddRange(Favorites[key].Select(s => new FeedArticle { Description = s.Description, SourceLink = key.Url, HaveBeenRed = true, IsFavorite = true, Link = s.Url, Title = s.Title, PublicationDate = s.PublicationDate, SourceName = key.Title }));
      }

      return PartialView("FeedArticlesList", Articles.OrderByDescending(o => o.PublicationDate));
    }

    private IEnumerable<FeedArticle> GetRssFeeds(string url)
    {
      var rssFeed = XDocument.Load(url);

      return GetRssFeeds(rssFeed);
    }

    private IEnumerable<FeedArticle> GetRssFeeds(XDocument rssFeed)
    {
      var rssFeedOut = from item in rssFeed.Descendants("item")
                       select new FeedArticle(item);
      return rssFeedOut;
    }
  }
}